<?php

namespace app\socket\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use Workerman\Worker;
use Workerman\Lib\Timer;

class Socket extends Command
{
    protected $socket = 'websocket://127.0.0.1:2345';
    /**
     * 命令Input配置
     */
    protected function configure()
    {
        $this->setName('socket')
            ->addArgument('action', Argument::OPTIONAL, "action")
            ->addOption('other', '-d', Option::VALUE_OPTIONAL, 'test');
    }

    /**
     * 重置Cli参数
     */
    protected function resetCli()
    {
        global $argv, $argc;

        $file = "{$argv['0']} {$argv['1']}";
        $action = $argv['2'];
        $extend = empty($argv['3']) ? '' : $argv['3'];
        $argv = [];
        $argv[] = $file;
        $argv[] = $action;
        if ($extend) {
            $argv[] = $extend;
        }
        $argc = count($argv);

        $_SERVER['argv'] = $argv;
        $_SERVER['argc'] = $argc;
    }

    /**
     * 命令响应
     * @param Input $input
     * @param Output $output
     * @return int|void|null
     */
    protected function execute(Input $input, Output $output)
    {

        //01.重置Cli命令行参数
        $this->resetCli();

        //02.开始WorkMan代码
        $ws_worker = new Worker("tcp://0.0.0.0:2347");

        // 启动4个进程对外提供服务
        $ws_worker->count = 4;
        

        // 接收到浏览器发送的数据时回复hello world给浏览器
        $ws_worker->onMessage = function ($connection, $data) {

            // 向浏览器发送hello world
            $connection->send('hello ' . $data);
        };

        // 运行worker
        Worker::runAll();
    }
}
/**
 * php think socket start  启动命令
 */
